package com.starblink.login.createaccount.inputpsw.ui

import com.alibaba.android.arouter.facade.annotation.Route
import com.starblink.basic.route.RoutePage
import com.starblink.android.basic.base.activity.BaseTVMActivity
import android.os.Bundle
import android.view.View
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.extension.navigation
import com.starblink.android.basic.user.login.LoginManager
import com.starblink.basic.style.R
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.KeyboardUtils
import com.starblink.login.createaccount.register.ui.CreateAccountRegisterActivity
import com.starblink.login.databinding.ActivityCreateAccountInputPswBinding
/**
 * 创建账户-输入密码
 */
@Route(path = RoutePage.Login.CREATE_ACCOUNT_INPUT_PSW)
class CreateAccountInputPswActivity :
    BaseTVMActivity<ActivityCreateAccountInputPswBinding, CreateAccountInputPswVM>() {

    override fun initViewBinding(): ActivityCreateAccountInputPswBinding =
        ActivityCreateAccountInputPswBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewBinding.etPassword.setOnEditInputListener {
            viewBinding.tvErrorHint.visibility = View.GONE
            viewBinding.btnContinue.isEnabled = !it.isEmpty()
        }

        viewBinding.btnContinue.isEnabled = LoginManager.validatePassword(viewBinding.etPassword.text) == null
        viewBinding.btnContinue.setOnClickListener {
            val res = LoginManager.validatePassword(viewBinding.etPassword.text)
            if (res == null) { // 输入密码OK
                if(!viewModel.isAgreePolicy){
                    toast(CommUtils.getString(R.string.accept_policy))
                    return@setOnClickListener
                }

                mActivity.navigation(
                    RoutePage.Login.CREATE_ACCOUNT_REGISTER,
                    Bundle().apply {
                        putString(
                            CreateAccountRegisterActivity.EXTRA_EMAIL, intent.getStringExtra(
                            EXTRA_EMAIL
                        ))
                        putString(CreateAccountRegisterActivity.EXTRA_PSW, viewBinding.etPassword.text.trim())
                    })
            } else {
                viewBinding.tvErrorHint.visibility = View.VISIBLE
                viewBinding.tvErrorHint.text = res
            }
        }

        //用户协议
        viewBinding.lgChoice.isChecked = viewModel.isAgreePolicy
        viewBinding.lgChoice.setOnClickListener {
            viewModel.isAgreePolicy = !viewModel.isAgreePolicy
            viewBinding.lgChoice.isChecked = viewModel.isAgreePolicy
        }
        LoginManager.setPrivacyPolicy(viewBinding.lgTxtService)

        //默认显示软键盘
        KeyboardUtils.openSoftKeyboard(this, viewBinding.etPassword.editText)
    }

    companion object {
       const val EXTRA_EMAIL = "EXTRA_EMAIL"
    }
}